<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>Create a layer from a portal item - 4.2</title>

  <style>
    html,
    body,
    #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
      overflow: hidden;
    }
  </style>

  <link rel="stylesheet" href="https://js.arcgis.com/4.2/esri/css/main.css">

  <script src="https://js.arcgis.com/4.2/"></script>

  <script>
    require([
      "esri/Map",
      "esri/views/MapView",
      "esri/layers/Layer",
      "esri/widgets/Legend",
      "dojo/domReady!"
    ], function(
      Map, MapView, Layer, Legend
    ) {

      var map = new Map({
        basemap: "gray"
      });

      var view = new MapView({
        map: map,
        container: "viewDiv",
        center: [ -100, 40],
        zoom: 4
      });
      
      view.then(function(){
        var legend = new Legend({
          view: view
        });
        view.ui.add(legend, "bottom-left");
      });

      /************************************************
       *
       * Create a layer from an existing Portal item hosted
       * in ArcGIS Online using the ID of the item.
       * 
       *************************************************/
      Layer.fromPortalItem({
          portalItem: { // autocast as esri/portal/PortalItem
            id: "05b6108388d14204a61cf1fc410bf5f4"
          }
        }).then(addLayer)
        .otherwise(rejection);

      // Adds the layer to the map once it loads
      function addLayer(lyr) {
        map.add(lyr);
      }

      function rejection(err) {
        console.log("Layer failed to load: ", err);
      }
    });
  </script>
</head>

<body>
  <div id="viewDiv"></div>
</body>

</html>